<?php
    namespace app\admin\controller;
    use app\common\controller\Common as base;
    use think\Db;
    
    class User extends base
    {
        //查询用户列表
        public function userList()
        {
            $data=Db::query("select * from user order by id desc");
            count($data) ? $this->resSuccess($data) : $this->resError(null); 
        }

        //查询用户信息
        public function userInfo()
        {
            $id=input('id');
            if(empty($id)){
                $this->resError('用户不存在');
                return ;
            }
            $data=Db::query("select * from user where id='$id'");
            count($data) ? $this->resSuccess($data[0]) : $this->resError(null); 
        }

        //登录
        public function login()
        {
            $userName=input('post.userName');
            $userPsw=input('post.userPsw');
            if(empty($userName)){
                $this->resError('用户名不能为空');
                return ;
            }else if(empty($userPsw)){
                $this->resError('密码不能为空');
                return ;
            }
            $userPsw=md5($userPsw);
            $res=db('user') -> where("userName = '$userName' AND userPsw = '$userPsw'") ->select();
            $res ? $this->resSuccess($res[0]) : $this->resError(null);
        }

        //添加用户
        public function userAdd()
        {
            $timestr=date('Ymdhis',time());
            $data=[
                "userName" => input('userName'),
                "userPsw" => md5(input('userPsw')),
                "userPhone" => input('userPhone'),
                "userCode" => 'T'.$timestr,
                "creatTime" => time(),
                "token" => md5(input('userPsw'))
            ];
            if(empty($data["userName"])){
                $this->resError('用户名不能为空');
                return ;
            }else if(empty($data['userPsw'])){
                $this->resError('密码不能为空');
                return ;
            }
            $ret=db('user')->where('userName',$data['userName'])->select();
            if($ret){
                $this->resError('用户名已存在');
                return ;
            }
            $res=db('user')->insert($data);
            $res ? $this->resSuccess($res) : $this->resError('添加失败'); 
        }

        //删除用户
        public function userDel()
        {
            $id=input('id');
            $res = db('user')->where('id',$id)->delete();
            $res ? $this->resSuccess(null) : $this->resError(null); 
        }

        //修改用户
        public function userEdit()
        {
            $id=input('id');
            $data=[
                "userName" => input('userName'),
                "userPhone" => input('userPhone')
            ];
            $res =db('user')->where('id',$id)->update($data);
            $res ? $this->resSuccess(null) : $this->resError(null);
        }
    }